
import 'package:flutter/cupertino.dart';

class ScrollUtil{
  ScrollUtil._();

  static void scrollToTarget(ScrollController controller,GlobalKey targetKey) {
    final context = targetKey.currentContext;
    if (context == null) return;
    if (!controller.hasClients) return;

    final RenderObject? targetObject = context.findRenderObject();
    if (targetObject is! RenderBox) return;

    final ScrollableState scrollable = Scrollable.of(context);
    final RenderObject? scrollRenderObject = scrollable.context.findRenderObject();
    if (scrollRenderObject is! RenderBox) return;

    final Offset targetInScroll =
    targetObject.localToGlobal(Offset.zero, ancestor: scrollRenderObject);
    double targetOffset = controller.offset + targetInScroll.dy;

    final double min = 0.0;
    final double max = controller.position.maxScrollExtent;
    if (targetOffset < min) targetOffset = min;
    if (targetOffset > max) targetOffset = max;

    controller.animateTo(
      targetOffset,
      duration: const Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    );
  }
}